<?php
/**
 * Created By virus_cms
 * Author: Virus
 * Date: 2020/3/1
 * Time: 17:06
 */

namespace app\admin\controller;


use app\admin\service\AdminService;
use app\admin\service\GroupService;
use app\common\lib\ImageUploadHandle;
use app\Request;
use think\App;

class Admin extends AdminBase
{
    protected $adminService = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->adminService = new AdminService();
    }

    /**
     * 管理员列表
     * @return \think\response\View
     */
    public function index()
    {
        try {
            $admins = $this->adminService->getAllAdmins();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        return view('admin/index', compact('admins'));
    }

    /**
     * 个人资料显示页面
     * @return \think\response\View
     */
    public function profile()
    {
        // 获取登录用户信息
        try {
            $admin_info = $this->adminService->getAdminByUid(session('session_admin.id'));
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        return view('admin/profile', compact('admin_info'));
    }

    /**
     * 个人资料设置
     * @param Request $request
     * @return \think\response\Json
     */
    public function setProfile(Request $request)
    {
        if (!$request->isPost() || !$request->isAjax()) {
            return writeJson(config('status.error'), "请求类型不合法");
        }

        $id   = $request->post('id', 0, 'intval');
        $data = [
            'nickname' => $request->post('nickname', '', 'trim'),
            'email'    => $request->post('email', '', 'trim'),
            'mobile'   => $request->post('mobile', '', 'trim'),
            'password' => $request->post('password', '', 'trim'),
        ];


        try {
            $result = $this->adminService->updateProfileById($id, $data);
        } catch (\Exception $e) {
            return writeJson(config('status.error'), $e->getMessage());
        }

        if ($result) {
            return writeJson(config('status.success'), "个人资料更新成功");
        }

        return writeJson(config('status.error'), "个人资料更新失败");
    }

    /**
     * 上传头像
     * @param Request $request
     * @param ImageUploadHandle $imageUploadHandle
     * @return \think\response\Json
     */
    public function uploadAvatar(Request $request, ImageUploadHandle $imageUploadHandle)
    {
        if (!$request->isPost() || !$request->isAjax()) {
            return writeJson(config('status.error'), "请求类型不合法");
        }

        $avatar = $request->file('avatar');
        $path   = $imageUploadHandle->save($avatar, 'avatar');

        // 将路径存储进入表中
        // 获取当前用户id
        $admin_id = session('session_admin.id');
        try {
            $result = $this->adminService->saveAvatar($admin_id, $path);
        } catch (\Exception $e) {
            return writeJson(config('status.error'), $e->getMessage());
        }

        $data = ['path' => $path];

        if ($result) {
            return writeJson(config('status.success'), "头像上传成功", $data);
        }

        return writeJson(config('status.error'), "上传失败");
    }

    /**
     * 获取所有的角色
     * @return array|\think\Collection
     */
    private function getRoles()
    {
        try {
            $roles = (new GroupService())->getAllGroups();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        return $roles;
    }

    /**
     * 添加管理员页面
     * @return \think\response\View
     */
    public function create()
    {
        $roles = $this->getRoles();

        return view('admin/create', compact('roles'));
    }

    /**
     * 添加管理员实现方法
     * @param Request $request
     * @return \think\response\Json
     */
    public function save(Request $request)
    {
        if (!$request->isPost() || !$request->isAjax()) {
            return writeJson(config('status.error'), "请求类型不合法");
        }

        $group_id = $request->post('group_id', 0, 'intval');
        $data     = [
            'nickname' => $request->post('nickname', '', 'trim'),
            'username' => $request->post('username', '', 'trim'),
            'password' => $request->post('password', '', 'trim'),
            'email'    => $request->post('email', '', 'trim'),
            'mobile'   => $request->post('mobile', '', 'trim'),
            'status'   => $request->post('status', 0, 'intval'),
        ];

        $res = $this->validate($data, "AdminValidate.add");
        if (true !== $res) {
            return writeJson(config('status.error'), $res);
        }

        try {
            $result = $this->adminService->addAdmin($group_id, $data);
        } catch (\Exception $e) {
            return writeJson(config('status.error'), $e->getMessage());
        }

        if ($result) {
            return writeJson(config('status.success'), "管理员添加成功");
        }

        return writeJson(config('status.error'), "管理员添加失败");
    }

    /**
     * 编辑管理员页面
     * @param $id
     * @return \think\response\View
     */
    public function edit($id)
    {
        try {
            $admin_one = $this->adminService->getOneAdminById($id);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $roles = $this->getRoles();

        return view('admin/edit', compact('admin_one', 'roles'));
    }

    /**
     * 编辑管理员的实现方法
     * @param Request $request
     * @return \think\response\Json
     */
    public function update(Request $request)
    {
        if (!$request->isPost() || !$request->isAjax()) {
            return writeJson(config('status.error'), "非法请求类型");
        }
        $id           = $request->post('id', 0, 'intval');
        $group_id     = $request->post('group_id', 0, 'intval');
        $data         = [
            'nickname' => $request->post('nickname', '', 'trim'),
            'username' => $request->post('username', '', 'trim'),
            'password' => $request->post('password', '', 'trim'),
            'email'    => $request->post('email', '', 'trim'),
            'mobile'   => $request->post('mobile', '', 'trim'),
            'status'   => $request->post('status', 0, 'intval'),
        ];
        $validateData = [
            'id'       => $id,
            'nickname' => $request->post('nickname', '', 'trim'),
            'username' => $request->post('username', '', 'trim'),
            'password' => $request->post('password', '', 'trim'),
            'email'    => $request->post('email', '', 'trim'),
            'mobile'   => $request->post('mobile', '', 'trim'),
            'status'   => $request->post('status', 0, 'intval'),
        ];
        $res          = $this->validate($validateData, "AdminValidate.edit");
        if (true !== $res) {
            return writeJson(config('status.error'), $res);
        }

        try {
            $result = $this->adminService->updateAdminAndGroupById($id, $group_id, $data);
        } catch (\Exception $e) {
            return writeJson(config('status.error'), $e->getMessage());
        }

        if ($result) {
            return writeJson(config('status.success'), "编辑管理员信息成功");
        }

        return writeJson(config('status.error'), "编辑管理员信息失败");
    }


    /**
     * 删除管理员
     * @param Request $request
     * @return \think\response\Json
     */
    public function delete(Request $request)
    {
        if (!$request->isPost() || !$request->isAjax()) {
            return writeJson(config('status.error'), "非法请求类型");
        }

        $id = $request->post('id', 0, 'intval');
        try {
            $res = $this->adminService->deleteAdminAndAccessGroupById($id);
        } catch (\Exception $e) {
            return writeJson(config('status.error'), $e->getMessage());
        }

        if ($res) {
            return writeJson(config('status.success'), '删除成功');
        }

        return writeJson(config('status.error'), '删除失败');
    }
}